import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * 自定义类加载器
 *
 * @author YooLin1c
 * @version 1.0.0
 * @since 2018-03-05 13:23
 */
public class MyClassLoader extends ClassLoader {
    /**
     * 要加载的Java类的classpath路径
     */
    private String classPath;

    public MyClassLoader(String classPath) {
        super(ClassLoader.getSystemClassLoader());
        this.classPath = classPath;
    }

    /**
     * 加载指定类至JVM内存中
     *
     * @param name 类的全限定名
     * @return 新加载后的类
     */
    @Override
    protected Class<?> findClass(String name) {
        byte[] b = this.loadClassData(name);
        return super.defineClass(name, b, 0, b.length);
    }

    /**
     * 加载class文件中的内容
     *
     * @param name 全限定名
     * @return 字节数组
     */
    private byte[] loadClassData(String name) {
        File file = new File(classPath.concat(name.replace(".", "/")).concat(".class"));
        try {
            while (!file.exists()) {
                Thread.sleep(500);

            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try (
                FileInputStream fis = new FileInputStream(file);
                ByteArrayOutputStream baos = new ByteArrayOutputStream()
        ) {
            int len;
            while ((len = fis.read()) != -1) {
                baos.write(len);
            }
            return baos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
